<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,100分)- 乱序整数序列两数之和绝对值最小（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给定一个随机的整数&#xff08;可能存在正整数和负整数&#xff09;数组 nums&#xff0c;请你在该数组中找出两个数&#xff0c;其和的绝对值(<strong>|nums[x]&#43;nums[y]|</strong>)为最小值&#xff0c;并返回这个两个数&#xff08;按从小到大返回&#xff09;以及绝对值。</p> 
<p>每种输入只会对应一个答案。但是&#xff0c;数组中同一个元素不能使用两遍。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>一个通过空格分割的有序整数序列字符串&#xff0c;最多1000个整数&#xff0c;且整数数值范围是 [-65535, 65535]。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>两数之和绝对值最小值</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">-1 -3 7 5 11 15</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">-3 5 2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">因为 |nums[0] &#43; nums[2]| &#61; |-3 &#43; 5| &#61; 2 最小&#xff0c;所以返回 -3 5 2。</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题数量级不大&#xff0c;可以考虑暴力破解。</p> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();
    System.out.println(getResult(nums));
  }

  public static String getResult(int[] nums) {
    int min &#61; Integer.MAX_VALUE;
    String ans &#61; &#34;&#34;;

    for (int i &#61; 0; i &lt; nums.length; i&#43;&#43;) {
      for (int j &#61; i &#43; 1; j &lt; nums.length; j&#43;&#43;) {
        int sum &#61; Math.abs(nums[i] &#43; nums[j]);
        if (min &gt; sum) {
          min &#61; sum;
          ans &#61; (nums[i] &lt; nums[j] ? nums[i] &#43; &#34; &#34; &#43; nums[j] : nums[j] &#43; &#34; &#34; &#43; nums[i]) &#43; &#34; &#34; &#43; sum;
        }
      }
    }

    return ans;
  }
}
</code></pre> 
<p></p> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  const nums &#61; line.split(&#34; &#34;).map(Number);
  console.log(getResult(nums));
});

function getResult(nums) {
  let min &#61; Infinity;
  let ans &#61; &#34;&#34;;

  for (let i &#61; 0; i &lt; nums.length; i&#43;&#43;) {
    for (let j &#61; i &#43; 1; j &lt; nums.length; j&#43;&#43;) {
      const sum &#61; Math.abs(nums[i] &#43; nums[j]);
      if (min &gt; sum) {
        min &#61; sum;
        ans &#61;
          nums[i] &lt; nums[j]
            ? &#96;${nums[i]} ${nums[j]} ${sum}&#96;
            : &#96;${nums[j]} ${nums[i]} ${sum}&#96;;
      }
    }
  }

  return ans;
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
import sys

nums &#61; list(map(int, input().split()))


# 算法入口
def getResult():
    minV &#61; sys.maxsize
    ans &#61; &#34;&#34;

    for i in range(len(nums)):
        for j in range(i &#43; 1, len(nums)):
            sumV &#61; abs(nums[i] &#43; nums[j])
            if minV &gt; sumV:
                minV &#61; sumV
                ans &#61; f&#34;{nums[i]} {nums[j]} {sumV}&#34; if nums[i] &lt; nums[j] else f&#34;{nums[j]} {nums[i]} {sumV}&#34;

    return ans


# 算法调用
print(getResult())
</code></pre> 
<p></p> 
<h4>优化解法</h4> 
<p>本题的优化思路是&#xff1a;</p> 
<p>首先将nums数组升序&#xff0c;nums数组长度为n</p> 
<ul><li>若nums数组全是非负数&#xff0c;比如nums &#61; [0,1,2,3,4]&#xff0c;则绝对值最小和 &#61; nums[0] &#43; nums[1]</li><li>若nums数组全是负数&#xff0c;比如nums &#61; [-4,-3,-2,-1]&#xff0c;则绝对值最小和 &#61; nums[n-2] &#43; nums[n-1]</li><li>若nums数组有非负数&#xff0c;也有负数&#xff0c;假设第一个非负数位置是idx&#xff0c;那么此时绝对值最小和可能是&#xff1a;</li></ul> 
<ol><li>非负数部分的前两个值&#xff1a;nums[idx] &#43; nums[idx&#43;1]</li><li>负数部分最后两个值&#xff1a;nums[idx-2] &#43; nums[idx-1]</li><li>非负positive &#43; 负negative的组合&#xff0c;组合中 -negative和positive必然是最接近&#xff0c;此时才能保证组合的和的绝对值最小</li></ol> 
<p></p> 
<p>找第一个非负数位置是idx&#xff0c;我们可以使用二分查找目标值0在nums中的<span style="color:#fe2c24;">有序插入位置</span>&#xff1a;</p> 
<ul><li>如果idx &#61;&#61; 0&#xff0c;那么说明nums中全是非负数</li><li>如果idx &#61;&#61; n&#xff0c;那么说明nums中全是负数</li><li>如果0 &lt; idx &lt; n&#xff0c;那么说明nums中既又负数&#xff0c;也有非负数&#xff0c;其中[0, idx-1]是负数部分&#xff0c;[idx, n-1]是非负数部分</li></ul> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();
    System.out.println(getResult(nums));
  }

  public static String getResult(int[] nums) {
    Arrays.sort(nums);

    int idx &#61; Arrays.binarySearch(nums, 0);
    if (idx &lt; 0) idx &#61; -idx - 1;

    // 全正数&#xff0c;或者 0&#43;多个正数
    if (idx &#61;&#61; 0) return nums[0] &#43; &#34; &#34; &#43; nums[1] &#43; &#34; &#34; &#43; (nums[0] &#43; nums[1]);

    int n &#61; nums.length;
    // 全负数&#xff0c;或者 多个负数&#43;0
    if (idx &gt;&#61; n - 1)
      return nums[n - 2] &#43; &#34; &#34; &#43; nums[n - 1] &#43; &#34; &#34; &#43; Math.abs(nums[n - 2] &#43; nums[n - 1]);

    // 下面是有正有负的处理逻辑
    int[] min &#61; {Integer.MAX_VALUE};
    String[] ans &#61; {&#34;&#34;};

    // 负数部分最后两个值
    if (idx &gt;&#61; 2) {
      check(min, ans, nums[idx - 2], nums[idx - 1]);
    }

    // 非负数部分的前两个值
    if (idx &lt; n - 1) {
      check(min, ans, nums[idx], nums[idx &#43; 1]);
    }

    // 非负数部分的数组
    int[] positive &#61; Arrays.copyOfRange(nums, idx, n);
    for (int i &#61; 0; i &lt; idx; i&#43;&#43;) {
      // 注意通过二分查找-nums[i]在positive的有序插入位置j&#xff0c;则最接近-nums[i]的值的位置有两个&#xff1a;j-1和j&#xff0c;其中j位置的元素值 &gt;&#61; -nums[i]&#xff0c;而j -
      // 1位置的元素值 &lt; -nums[i]
      int j &#61; Arrays.binarySearch(positive, -nums[i]);

      if (j &lt; 0) j &#61; -j - 1;
      if (j &#61;&#61; positive.length) j -&#61; 1;

      check(min, ans, nums[i], positive[j]);

      if (j - 1 &gt;&#61; 0) {
        check(min, ans, nums[i], positive[j - 1]);
      }
    }

    return ans[0];
  }

  public static void check(int[] min, String[] ans, int num1, int num2) {
    int sum &#61; Math.abs(num1 &#43; num2);
    if (min[0] &gt; sum) {
      min[0] &#61; sum;
      ans[0] &#61; num1 &#43; &#34; &#34; &#43; num2 &#43; &#34; &#34; &#43; sum;
    }
  }
}
</code></pre> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  const nums &#61; line.split(&#34; &#34;).map(Number);
  console.log(getResult(nums));
});

function getResult(nums) {
  nums.sort((a, b) &#61;&gt; a - b);

  let idx &#61; binarySearch(nums, 0);
  if (idx &lt; 0) idx &#61; -idx - 1;

  // 全正数&#xff0c;或者 0&#43;多个正数
  if (idx &#61;&#61; 0) return nums[0] &#43; &#34; &#34; &#43; nums[1] &#43; &#34; &#34; &#43; (nums[0] &#43; nums[1]);

  const n &#61; nums.length;
  // 全负数&#xff0c;或者 多个负数&#43;0
  if (idx &gt;&#61; n - 1)
    return (
      nums[n - 2] &#43;
      &#34; &#34; &#43;
      nums[n - 1] &#43;
      &#34; &#34; &#43;
      Math.abs(nums[n - 2] &#43; nums[n - 1])
    );

  // 下面是有正有负的处理逻辑
  const min &#61; [Infinity];
  const ans &#61; [&#34;&#34;];

  // 负数部分最后两个值
  if (idx &gt;&#61; 2) check(min, ans, nums[idx - 2], nums[idx - 1]);

  // 非负数部分的前两个值
  if (idx &lt; n - 1) check(min, ans, nums[idx], nums[idx &#43; 1]);

  // 非负数部分的数组
  const positive &#61; nums.slice(idx);
  for (let i &#61; 0; i &lt; idx; i&#43;&#43;) {
    // 注意通过二分查找-nums[i]在positive的有序插入位置j&#xff0c;则最接近-nums[i]的值的位置有两个&#xff1a;j-1和j&#xff0c;其中j位置的元素值 &gt;&#61; -nums[i]&#xff0c;而j -
    // 1位置的元素值 &lt; -nums[i]
    let j &#61; binarySearch(positive, -nums[i]);

    if (j &lt; 0) j &#61; -j - 1;
    if (j &#61;&#61; positive.length) j -&#61; 1;

    check(min, ans, nums[i], positive[j]);

    if (j - 1 &gt;&#61; 0) {
      check(min, ans, nums[i], positive[j - 1]);
    }
  }

  return ans[0];
}

function check(min, ans, num1, num2) {
  const sum &#61; Math.abs(num1 &#43; num2);
  if (min[0] &gt; sum) {
    min[0] &#61; sum;
    ans[0] &#61; &#96;${num1} ${num2} ${sum}&#96;;
  }
}

function binarySearch(arr, target) {
  let low &#61; 0;
  let high &#61; arr.length - 1;

  while (low &lt;&#61; high) {
    const mid &#61; (low &#43; high) &gt;&gt; 1;
    const midVal &#61; arr[mid];

    if (midVal &gt; target) {
      high &#61; mid - 1;
    } else if (midVal &lt; target) {
      low &#61; mid &#43; 1;
    } else {
      return mid;
    }
  }

  return -low - 1;
}
</code></pre> 
<h4>Python算法源码</h4> 
<pre><code class="language-python">import sys

# 输入获取
nums &#61; list(map(int, input().split()))


def binarySearch(arr, target):
    low &#61; 0
    high &#61; len(arr) - 1

    while low &lt;&#61; high:
        mid &#61; (low &#43; high) &gt;&gt; 1
        midVal &#61; arr[mid]

        if midVal &gt; target:
            high &#61; mid - 1
        elif midVal &lt; target:
            low &#61; mid &#43; 1
        else:
            return mid

    return -low - 1


def check(minV, ans, num1, num2):
    sumV &#61; abs(num1 &#43; num2)
    if minV[0] &gt; sumV:
        minV[0] &#61; sumV
        ans[0] &#61; f&#34;{num1} {num2} {sumV}&#34;


# 算法入口
def getResult():
    nums.sort()

    idx &#61; binarySearch(nums, 0)
    if idx &lt; 0:
        idx &#61; -idx - 1

    # 全正数&#xff0c;或者 0&#43;多个正数
    if idx &#61;&#61; 0:
        return f&#34;{nums[0]} {nums[1]} {nums[0] &#43; nums[1]}&#34;

    n &#61; len(nums)
    # 全负数&#xff0c;或者 多个负数&#43;0
    if idx &gt;&#61; n-1:
        return f&#34;{nums[n-2]} {nums[n-1]} {abs(nums[n-2] &#43; nums[n-1])}&#34;

    # 下面是有正有负的处理逻辑
    minV &#61; [sys.maxsize]
    ans &#61; [&#34;&#34;]

    # 负数部分最后两个值
    if idx &gt;&#61; 2:
        check(minV, ans, nums[idx-2], nums[idx-1])

    # 非负数部分的前两个值
    if idx &lt; n-1:
        check(minV, ans, nums[idx], nums[idx&#43;1])

    # 非负数部分的数组
    positive &#61; nums[idx:]
    for i in range(0, idx):
        # 注意通过二分查找-nums[i]在positive的有序插入位置j&#xff0c;则最接近-nums[i]的值的位置有两个&#xff1a;j-1和j&#xff0c;其中j位置的元素值 &gt;&#61; -nums[i]&#xff0c;而j - 1位置的元素值 &lt; -nums[i]
        j &#61; binarySearch(positive, -nums[i])

        if j &lt; 0:
            j &#61; -j - 1

        if j &#61;&#61; len(positive):
            j -&#61; 1

        check(minV, ans, nums[i], positive[j])

        if j - 1 &gt;&#61; 0:
            check(minV, ans, nums[i], positive[j-1])

    return ans[0]


# 算法调用
print(getResult())
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>